import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Hashtable;


public class Saver {
	
	public static String newline = System.getProperty("line.separator");
	
	public static Hashtable<String, String> dicArts = new Hashtable<String, String>();
	
	public static void Save(ArrayList<ArticleDetails> arrArtic, BotConfig cfg) throws Exception{
		
		String outPutDir = cfg.getOutPutFolder();
		
		File parDir = new File(outPutDir);
		if(parDir.exists() == false)
			parDir.mkdir();
		if(outPutDir.endsWith(File.separator) == false)
    		outPutDir += File.separator;
		
		FileOutputStream labSt = null;
		OutputStreamWriter labWr = null;
    	
		try
		{
			String artsLabels = outPutDir + "articles.txt";
			File labFile = new File(artsLabels);
			if(labFile.exists() && dicArts.size() == 0) {
				FileInputStream labInS = new FileInputStream(labFile);
				InputStreamReader r = new InputStreamReader(labInS);
				BufferedReader br = new BufferedReader(r);
				
				String theLine;
				while ((theLine = br.readLine()) != null) {
					String[] sts = theLine.split(" ~#~ ");
					if(sts.length == 2){
						dicArts.put(sts[0], sts[1]);
					}
				}				  
				labInS.close();
				r.close();
				br.close();
			}
			labSt = new FileOutputStream(labFile);
			labWr = new OutputStreamWriter(labSt);
			
			String allCnt = Integer.toString(arrArtic.size());
			int pos = 0;
			
			for (ArticleDetails articleDetails : arrArtic) {
				++pos;
				InputStream is = null;	    
				
			    OutputStream artSt = null;
			    OutputStream descSt = null;
			    OutputStreamWriter wrDesc = null;
				
			    try
			    {
			    	if(cfg.getExtLoging()){
						System.out.println("Artykułu " + Integer.toString(pos) + " z " + allCnt);
					}
			    	if(articleDetails.getUrl() == null || articleDetails.getUrl() == "")
			    	{   
			    		System.out.println("Brak adresu dla " + articleDetails.getTitle());
			    		continue;
			    	}
			    	
			    	if(dicArts.containsKey(articleDetails.getUrl()))
			    		continue;
			    			    	
			    	String artFileDirName = articleDetails.getTitle();
			    	StringBuffer buf = new StringBuffer();
			    	for(int i=0;i<artFileDirName.length();++i)
			    	{
			    		if((artFileDirName.charAt(i) >= 65 && artFileDirName.charAt(i) <= 90) ||
			    				(artFileDirName.charAt(i) >= 92 && artFileDirName.charAt(i) <= 122)) 
			    			buf.append(artFileDirName.charAt(i));
			    	}
			    	artFileDirName = buf.toString();
			    	if(artFileDirName.isEmpty())
			    		artFileDirName = "Artykul";
			    	
			    	String strbase = artFileDirName;
			    	String artDirPath = outPutDir + artFileDirName;
			    	File artDir = new File(artDirPath);
			    	
			    	int idx = 1;			    	
			    	while(artDir.exists())
			    	{
			    		artFileDirName = strbase + Integer.toString(idx);
			    		++idx;
			    		
			    		artDirPath = outPutDir + artFileDirName;
				    	artDir = new File(artDirPath);
			    	}			    	
			    	dicArts.put(articleDetails.getUrl(), artFileDirName);
			    				    	
			    	if(artDir.exists() == false)
			    		artDir.mkdir();
			    	
			    	  	
			    	if(cfg.getExtLoging()){
						System.out.println("Sciąganie artykułu: " + articleDetails.getTitle() + " do " + artDirPath);
					}
			    	
			    	if(artDirPath.endsWith(File.separator) == false)
			    		artDirPath = artDirPath + File.separator;
			    	
			    	File descFile = new File(artDirPath + "desc.txt");
			    	File artFile = new File(artDirPath + "art.pdf");
			    	
			    	descSt = new FileOutputStream(descFile);
			    	wrDesc = new OutputStreamWriter(descSt);
			    	wrDesc.write("Title: " + articleDetails.getTitle() + newline);
			    	if(articleDetails.getYear() != null)
			    		wrDesc.write("Date: " + articleDetails.getYear() + newline);
			    	if(articleDetails.getKeywords() != null)
			    		wrDesc.write("Keywords: " + articleDetails.getKeywords() + newline);
			    	if(articleDetails.getDesc() != null)
			    		wrDesc.write("Abstract: " + articleDetails.getDesc() + newline);
			    	wrDesc.write("Url: " + articleDetails.getUrl() + newline);
			    	wrDesc.flush();
			    	
				    URL url = new URL(articleDetails.getUrl());
				    URLConnection conn = url.openConnection();
				    
				    is = conn.getInputStream();
				    artSt = new FileOutputStream(artFile);
				    
				    int nextChar;
				    while ( ( nextChar = is.read() ) != -1  )
				    	artSt.write(nextChar);
				    artSt.flush();
				}
			    finally
			    {
			    	if(is != null)
			    		is.close();
			    	if(artSt != null)
			    		artSt.close();
			    	if(descSt != null)
			    		descSt.close();
			    	if(wrDesc != null)
			    		wrDesc.close();
			    }
			}
		}
		finally
		{
			if(labSt != null)
				labSt.close();
			if(labWr != null)
				labWr.close();
		}
	}

}
